import 'dart:developer' as developer;
import 'package:get/get.dart';
import '../../../core/repository/default_api.dart';
import '../../../services/device_sn_manager.dart';

/// 活动日历控制器
class ActivityCalendarLogic extends GetxController {
  static const String _tag = 'ActivityCalendarLogic';

  final RxBool _isLoading = true.obs;
  final RxInt _currentYear = DateTime.now().year.obs;
  final RxMap<String, Map<String, dynamic>> _calendarData =
      <String, Map<String, dynamic>>{}.obs;

  bool get isLoading => _isLoading.value;
  int get currentYear => _currentYear.value;

  @override
  void onInit() {
    super.onInit();
    _fetchCalendarData();
  }

  /// 获取日历数据
  Future<void> _fetchCalendarData() async {
    try {
      _isLoading.value = true;
      developer.log('📅 开始获取活动日历数据...', name: _tag);

      // 获取设备SN
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();

      if (deviceSn.isEmpty) {
        developer.log('⚠️ 设备SN为空，无法获取日历数据', name: _tag);
        return;
      }

      final response = await DefaultApi().queryActivityCalendarListGet(
        deviceSn: deviceSn,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      developer.log('✅ 活动日历数据获取成功: $response', name: _tag);

      // 解析数据
      if (response != null && response['data'] != null) {
        final List<dynamic> dataList = response['data'];
        _calendarData.clear();

        for (var item in dataList) {
          final dailyValue = item['dailyValue'] as String;
          _calendarData[dailyValue] = {
            'week': item['week'],
            'steps': item['steps'] ?? 0,
            'duration': item['duration'] ?? 0,
            'calorie': item['calorie'] ?? 0,
            'stepCount': item['stepCount'] ?? 0,
            'exerciseDuration': item['exerciseDuration'] ?? 0,
            'exerciseCalorie': item['exerciseCalorie'] ?? 0,
          };
        }

        developer.log('✅ 活动日历数据解析成功，共${_calendarData.length}天', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 获取活动日历数据失败: $e', name: _tag);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 获取指定日期的数据
  Map<String, dynamic>? getDayData(String dateStr) {
    return _calendarData[dateStr];
  }

  /// 获取需要显示的月份列表
  List<int> getMonthsToDisplay() {
    final now = DateTime.now();
    // 显示当前月份及之前的月份
    return List.generate(now.month, (index) => index + 1);
  }

  /// 日期选中回调
  void onDateSelected(String dateStr) {
    developer.log('📅 选中日期: $dateStr', name: _tag);
    // 返回上一页并传递选中的日期
    Get.back(result: dateStr);
  }
}
